#!/bin/bash
DIR_data=`pwd`
gain=2.0
rdnoise=10.0
listflat=$1
if [ $# -ne 1  ]
then
	echo "usage[ xflatcom.sh listflat  ]"
	exit 0
fi


darkname=Zero.fit
firstimg=`head -1 $listflat`
filter=`gethead $firstimg "FILTER"`
outputimg=`echo "Flat_"$filter".fit"`
if test -r $darkname
then
	echo "----Doing the flat process----"
	cd $HOME/iraf
	cp -f login.cl.old login.cl
	echo noao >> login.cl
	echo imred >>login.cl
	echo ccdred >>login.cl
	echo "cd $DIR_data" >> login.cl
	echo "ccdpro((images=\"@$listflat\", output=\"  \",trim-,zerocor+,darkcor-,flatcor-,zero=\"$darkname\")" >>login.cl
	echo "flatcombine(input=\"@$listflat\", output=\"$outputimg\",combine=\"median\",reject=\"minmax\",ccdtyp=\" \",process-,rdnoise=$rdnoise,gain=$gain,)" >>login.cl
	echo "display(image=\"Flat\",frame=1)" >>login.cl
	echo logout >> login.cl
	cl < login.cl >xlogfile 
	cd $HOME/iraf
	cp -f login.cl.old login.cl
	cd $DIR_data
else
	
	echo "No Zero.fit"
	echo "----Doing the flat process----"
	cd $HOME/iraf
	cp -f login.cl.old login.cl
	echo noao >> login.cl
	echo imred >>login.cl
	echo ccdred >>login.cl
	echo "cd $DIR_data" >> login.cl
	echo "flatcombine(input=\"@$listflat\", output=\"$outputimg\",combine=\"median\",reject=\"minmax\",ccdtyp=\" \",process-,rdnoise=$rdnoise,gain=$gain,)" >>login.cl
	echo "display(image=\"Flat\",frame=1)" >>login.cl
	echo logout >> login.cl
	cl < login.cl >xlogfile 
	cd $HOME/iraf
	cp -f login.cl.old login.cl
	cd $DIR_data
fi
